import axios from 'axios'
import config from './config'
import { ElMessage } from 'element-plus'
// import { useRouter } from 'vue-router';

// const router = useRouter()
const instance = axios.create({
  baseURL: config.baseApi,
  timeout: 8000,
});


// 添加请求拦截器
instance.interceptors.request.use(function (req) {
  // 在发送请求之前做些什么
  const headers = req.headers
  if(headers.Authorization) headers.Authorization = 'Bear Jack'
  return req;
});

// 添加响应拦截器
instance.interceptors.response.use(function (res) {
  const { result_code, data, result_msg } = res.data

  if(result_code == 0) {
    return data;
  }  else {
    ElMessage.error(result_msg)
    return Promise.reject(result_msg);
  } 
});

function request(options){
  options.method = options.method || 'get'
  if(options.method.toLowerCase() === 'get'){
    options.params = options.data
  }

  if(config.env === 'prod'){
    instance.defaults.baseURL = config.baseApi
  } else {
    instance.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
  }
  return instance(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
  request[item] = (url, data, options) => {
    return request({
      method: item,
      url,
      data,
      ...options,
    })
  }
})

export default request